package com.kami.realm;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.kami.dao.SysUserMapper;
import com.kami.entity.SysResource;
import com.kami.entity.SysUser;
import com.kami.entity.SysUserExample;
import com.kami.entity.SysUserExample.Criteria;
import com.kami.service.SysResourceService;
import com.kami.service.SysUserService;

public class ShiroRealm extends AuthorizingRealm{

	@Autowired
	private SysUserMapper sysUserMapper;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysResourceService sysResourceService;
	
    /**
     * Shiro权限认证
     */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SysUser user = (SysUser) principals.getPrimaryPrincipal();
		Long userId = user.getId();
		
		List<String> permsList = new ArrayList<>();
		if (userId == 1) {
			//  管理员最高权限
			List<SysResource> list = sysResourceService.selectAll();
			for (SysResource sysResource : list) {
				permsList.add(sysResource.getPerms());
			}
		}else {
			permsList = sysUserService.findAllPerms(userId);
		}
		
		Set<String> permsSet = new HashSet<String>();
		for(String perms : permsList){
			if(StringUtils.isBlank(perms)){
				continue;
			}
			permsSet.addAll(Arrays.asList(perms.trim().split(",")));
		}
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setStringPermissions(permsSet);
		return info;
	}

    /**
     * Shiro登录认证(原理：用户提交 用户名和密码  --- shiro 封装令牌 ---- realm 通过用户名将密码查询返回 ---- shiro 自动去比较查询出密码和用户输入密码是否一致---- 进行登陆控制 )
     */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		
		String username = upToken.getUsername();
		SysUser user = sysUserMapper.selectByLoginName(username);
		
		
		if(null == user){
			throw new UnknownAccountException("用户不存在！");
		}
		
		String credentials = user.getPassword();
		
		String realmName = getName();
		
		ByteSource credentialsSalt = ByteSource.Util.bytes(username);
		SimpleAuthenticationInfo info = 
				new SimpleAuthenticationInfo(user, credentials,credentialsSalt, realmName);
			
		return info;
	}
	
	public static void main(String[] args) {
		String hashAlgorithmName = "MD5";
//		String hashAlgorithmName = "SHA1";
		Object credentials = "123456";
		Object salt = ByteSource.Util.bytes("admin");
		int hashIterations = 1;
		
		Object result = new SimpleHash(hashAlgorithmName, credentials,salt, hashIterations);
		SimpleHash hash = new SimpleHash(hashAlgorithmName, credentials,salt, hashIterations);
		System.out.println(hash.toString());
		System.out.println(hash.toHex());
		System.out.println(hash.toBase64());
		System.out.println(result);
	}

}
